package DGWeb.Servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.joda.time.Seconds;

import DGWeb.AppConstants;
import DGWeb.Model.AbstractGet;
import DGWeb.Model.Comments;
import DGWeb.Model.SendMessageToClient;

import com.google.gson.Gson;

/**
 * Servlet implementation class getComments
 */
@SuppressWarnings("deprecation")
@WebServlet("/getComments")
public class getComments extends HttpServlet  implements SingleThreadModel {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public getComments() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Context context = null;
		BasicDataSource ds = null;
		Connection conn = null;
		Statement stmt = null;
		String CommentsJsonResult = null;
		PrintWriter out = response.getWriter();
		response.setContentType("html");
		
		Gson json = new Gson();
		int msgId;
		@SuppressWarnings("unchecked")
		Collection<Comments> CommentsResult = (Collection<Comments>)getServletContext().getAttribute(AppConstants.COMMENTS_TABLE);

		InputStreamReader isr = new InputStreamReader(request.getInputStream());
		BufferedReader br = new BufferedReader(isr);
		msgId = json.fromJson(br.readLine().toString(), SendMessageToClient.class ).getId() ;
		br.close();
		isr.close();		
		
		try 
		{
			context = new InitialContext();
			ds = (BasicDataSource)context.lookup(AppConstants.DB_DATASOURCE);
			conn = ds.getConnection();
			//create Customers table
			stmt = conn.createStatement();			

			Collection<Comments> temp = new ArrayList<Comments>();
			String[] dt = AppConstants.GET_COMMENTS_SELECT.split("//");

			
			String exec = dt[0] +msgId +dt[1];
			ResultSet res = stmt.executeQuery(exec);

			while (res.next() )
			{
				String id = res.getString(AppConstants.COMMENTS_ID);
				String msgid= res.getString(AppConstants.COMMENTS_MESSAGE_ID);
				String Nickname= res.getString(AppConstants.COMMENTS_WHO_WROTE);
				String Text = res.getString(AppConstants.COMMENTS_TEXT);
				String Time = res.getString(AppConstants.COMMENTS_TIME);
				Time = calcTime(Time);
				// Check text for Users Or Topics
				Text = AbstractGet.chkUsersTopics(Text);
				
				Comments comment = new Comments(Integer.parseInt(id),Integer.parseInt(msgid),Text,Time,Nickname);
				temp.add(comment);
    			
			}
			CommentsResult = temp;

			
			//convert from customers collection to json
			CommentsJsonResult = json.toJson(CommentsResult , AppConstants.COMMENTS_COLLECTION );

			//CommentsResult.clear();
			conn.commit();
			stmt.close();
			conn.close();
			context.close();
			out.println(CommentsJsonResult);
			out.close();
			
		} 
		catch (NamingException |SQLException | ParseException e) {
			
			e.printStackTrace();

			try {
				if (stmt != null)
				stmt.close();
				if (context != null)
					context.close();
				if ( conn != null )
					conn.close();
			} catch (NamingException|SQLException e1) {
				
				e1.printStackTrace();
			}
		}
		
	}
	
	private String calcTime(String getTime) throws ParseException
	{
		String strTime="";
		DateFormat dateFormat = new SimpleDateFormat(AppConstants.TimeFormat);
		Date MessageDate = dateFormat.parse(getTime);
		DateTime msgDate = new DateTime(MessageDate);
		
		// get current time
		Date currtime = Calendar.getInstance().getTime();
		DateTime currentTime = new DateTime(currtime);
		
		int days = Days.daysBetween(msgDate,currentTime).getDays();
		int hours = Hours.hoursBetween(msgDate , currentTime).getHours();
		int minutes = Minutes.minutesBetween(msgDate , currentTime).getMinutes();
		int seconds= Seconds.secondsBetween( msgDate , currentTime).getSeconds();
		if (days >0)
		{
			strTime = msgDate.getDayOfMonth() +"/"+msgDate.getMonthOfYear()+"/"+msgDate.getYear()+" "+msgDate.getHourOfDay() +":"+msgDate.getMinuteOfHour();
			/*
			if ( days == 1){
				strTime= days +" Day ago";
			} else {
				strTime= days +" Days ago";
			}
			*/
		}
		else if (hours > 0 )
		{
			if (hours == 1){
				strTime= hours +" Hour ago";
			}else{
				strTime= hours +" Hours ago";
			}
		}
		else if (minutes > 0 )
		{
			if (minutes == 1){
				strTime= minutes +" Minute ago";
			}else{
				strTime= minutes +" Minutes ago";
			}
		}
		else if (seconds > 0 )
		{
			if (seconds == 1){
				strTime= seconds +" Second ago";
			}else{
				strTime= seconds +" Seconds ago";
			}
		
		}
		else
		{
			strTime= "Posted Now";
		}

		return strTime;
	}



}
